package com.zyg.controller;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zyg.pojo.Team;
import com.zyg.service.TeamService;
import com.zyg.util.LayData;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/team")
public class TeamController {
    @Resource
    private TeamService teamService;

    @RequestMapping("/tolist")
    public String tolist(){
        return "team/list";
    }
    @RequestMapping("/list")
    @ResponseBody
    public String list(Team team, @RequestParam(value = "page", defaultValue = "1") Integer page, @RequestParam(value = "limit", defaultValue = "10") Integer limit){
        LayData layData = new LayData();
        QueryWrapper<Team> qw = new QueryWrapper<>();
        qw.like(team.getTeamName()!=null&&!"".equals(team.getTeamName()),"team_name",team.getTeamName());
        long count = teamService.count(qw);
        layData.setCount((int)count);//强制转换
        //查询
        Page<Team> page1= new Page<>(page,limit);
        layData.setData(teamService.list(page1,qw));
        layData.setCode(0);
        layData.setMsg("查询成功");
        // 数据返回
        String data = JSON.toJSONString(layData);
        return data;
    }

    @RequestMapping("/toadd")
    public String toAdd(){
        return "team/add";
    }
    @RequestMapping("/addSave")
    @ResponseBody
    public String addSave(Team team){
        boolean flag = teamService.save(team);//save一般保存单个参数，saveBatch保存多个参数
        if(flag){
            return JSON.toJSONString(new LayData(0,"添加成功"));
        }else{
            return JSON.toJSONString(new LayData(500,"添加失败"));
        }
    }
    @RequestMapping("/toupdate/{id}")
    public String toUpdate(@PathVariable("id") Integer id, Model model){
        Team team = teamService.getById(id);
        model.addAttribute("team",team);
        return "team/update";
    }

    @RequestMapping("/updateSave")
    @ResponseBody
    public String updateSave(Team team){

        boolean update = teamService.updateById(team);
        if(update){
            return JSON.toJSONString(new LayData(0,"修改成功"));
        }else{
            return JSON.toJSONString(new LayData(500,"修改失败"));
        }
    }
    @RequestMapping("/delete/{id}")
    @ResponseBody
    public String deleteDept(@PathVariable("id") Integer id) {
        boolean remove = teamService.removeById(id);
        if (remove) {

            return JSON.toJSONString(new LayData(0, "删除成功"));
        } else {

            return JSON.toJSONString(new LayData(500, "删除失败"));
        }
    }
}